function [ChEstimate,error2] = LSChEstimate(ChOutput,ChInput,ChLength)
% ***************************************************
% 
% INPUTS:
%        ChOutput : The outputs of the channel sampled at one sample per symbol
%        ChInput  : The input symbols to the channel sampled at one sample per symbol 
%        ChLength : Length of composite channel
%
% OUTPUTS:
%       ChEstimate: estimated composite channel, i.e. (KnownCh*UnKnownCh)
%       error2    : square sum of the estimation error.
% ********************************************************

ResultSymbols = ChInput(:);
ChOutput=ChOutput(:);

ShiftedSymbols = convmtx(ResultSymbols,ChLength);
ShiftedSymbols = ShiftedSymbols(ChLength:length(ChInput),:);


%ChEstimate = inv(ShiftedSymbols' * ShiftedSymbols) * ShiftedSymbols' * ChOutput(ChLength:length(ChInput));
ChEstimate = pinv(ShiftedSymbols' * ShiftedSymbols) * ShiftedSymbols' * ChOutput(ChLength:length(ChInput));



yhat = conv(ChEstimate,ChInput) ;
yhat = yhat(1:length(ChOutput));

err = yhat(:) - ChOutput(:);

% normalized error sum
error2 = mean( abs(err).^2 );

